package net.sashag.nadlandroid;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

public class NavigationButtonGridAdapter extends BaseAdapter {
	
	private Context context;
	private List<NavigationGridItem> items = new ArrayList<NavigationGridItem>();
	
	public NavigationButtonGridAdapter(Context context) {
		this.context = context;
	}
	
	public void removeButton(String text) {
		int itemToRemove = -1;
		for (int i = 0; i < items.size(); ++i) {
			if (items.get(i).text.equals(text)) {
				itemToRemove = i;
				break;
			}
		}
		if (itemToRemove == -1)
			return;
		
		items.remove(itemToRemove);
		notifyDataSetChanged();
	}
	
	public void addButton(NavigationGridItem item) {
		if (item.icon == null) {
			item.icon = context.getResources().getDrawable(item.iconId);
		}
		items.add(item);
		notifyDataSetChanged();
	}
	
	public void addButton(String text, int iconId, Runnable action) {
		addButton(new NavigationGridItem(text, iconId, action));
	}
	
	public void addButton(String text, Drawable icon, Runnable action) {
		addButton(new NavigationGridItem(text, icon, action));
	}
	
	@Override
	public int getCount() {
		return items.size();
	}

	@Override
	public Object getItem(int position) {
		return items.get(position);
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final NavigationGridItem item = (NavigationGridItem)getItem(position);
		ImageButton button;
		TextView textView;
		if (convertView == null) {
			LayoutInflater inflater = LayoutInflater.from(context);
			convertView = inflater.inflate(R.layout.navbutton_item, null);
		}
		button = (ImageButton)convertView.findViewById(R.id.btnAction);
		button.setImageDrawable(item.icon);
		button.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				item.action.run();
			}
		});
		textView = (TextView)convertView.findViewById(R.id.txtDescription);
		textView.setText(item.text);
		textView.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				item.action.run();
			}
		});
		return convertView;
	}

}
